#ifndef UTILS_H_
#define UTILS_H_
#include <sstream>
#include <string>
#include "../Entities/Record.h"
#include "../Entities/TreeB+/RecordNode.h"
#include <vector>
#include <algorithm>
using namespace std;
using namespace Tree;

namespace Commons {

class Utils {

protected:
	Utils() {
	}

public:

	static string GetNextStringValue(stringstream* dataStream) {
		string toReturn;
		unsigned int stringLength = 0;
		char* tempValue;

		dataStream->read((char*) &stringLength, sizeof(int));
		tempValue = new char[stringLength];
		dataStream->read(tempValue, stringLength);
		toReturn = Utils::BuildString(tempValue, stringLength);

		delete tempValue;
		return toReturn;
	}

	static string BuildString(char* text, unsigned int length) {

		string toReturn;

		for (unsigned int i = 0; i < length; i++) {
			toReturn += text[i];
		}

		return toReturn;
	}

	static Record* getRecordIn(string key, vector<Record*>* collection) {
		Record* toReturn = NULL;
		for (unsigned i = 0; i < collection->size(); i++) {
			Record* current = collection->at(i);
			if (toReturn->getKey() == key) {
				toReturn = current;
				break;
			}
		}

		return toReturn;
	}

	static RecordNode* getRecordNodeIn(string key, vector<RecordNode*>* collection) {
		RecordNode* toReturn = NULL;
		for (unsigned i = 0; i < collection->size(); i++) {
			RecordNode* current = collection->at(i);
			if (toReturn->getKey() == key) {
				toReturn = current;
				break;
			}
		}

		return toReturn;
	}

	static void sortRecordsByKey(vector<RecordNode*>* collectionToSort) {

		sort(collectionToSort->begin(), collectionToSort->end(), sortRecordNodesByKey);
	}

	virtual ~Utils();

private:
	static bool sortRecordNodesByKey(RecordNode* a, RecordNode* b) {
			return (a->getKey() < b->getKey());
		}

};

}
#endif /* UTILS_H_ */
